const fs = require("fs");
const path = require("path");
const router = require("express").Router();

router.get("/img/*", (req, res) => {
    let root = path.dirname(path.dirname(__dirname));
    let name = decodeURI(req.originalUrl).split("/file/img/")[1], //获取到文件名
        base = path.basename(req.originalUrl.split("/file/img/")[1]); //获取后缀名

    fs.readFile(`${root}/uploads/imgs/${name}`, (err, data) => {
        if (err) {
            res.status(200).send({ message: err, ok: false });
        } else {
            res.status(200)
                .header("Content-Type", `image/${base}`)
                .end(data, "binary");
        }
    });
});

router.get("/voice/*", (req, res) => {
    let root = path.dirname(path.dirname(__dirname));
    let name = decodeURI(req.originalUrl).split("/file/voice/")[1], //获取到文件名
        base = path.basename(req.originalUrl.split("/file/voice/")[1]); //获取后缀名

    fs.readFile(`${root}/uploads/${name}`, (err, data) => {
        if (err) {
            res.status(200).send({ message: err, ok: false });
        } else {
            res.status(200)
                .header("Content-Type", `audio/${base}`)
                .end(data, "binary");
        }
    });
});

module.exports = router;
